{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{% if agent %}编辑智能体 - {{ agent.name }}{% else %}新建智能体{% endif %} - 数据源管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" />
    <style>
        .sidebar {
            height: 100vh;
            background-color: #343a40;
            color: white;
            padding-top: 20px;
        }
        .sidebar .nav-link {
            color: #adb5bd;
            border-radius: 0;
        }
        .sidebar .nav-link.active {
            background-color: #0d6efd;
            color: white;
        }
        .content {
            padding: 20px;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .table-selection {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #e9ecef;
            border-radius: 0.25rem;
            padding: 1rem;
        }
        .table-item {
            margin-bottom: 1rem;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            overflow: hidden;
        }
        .table-header {
            background-color: #f8f9fa;
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }
        .table-header:hover {
            background-color: #e9ecef;
        }
        .table-fields {
            padding: 0.75rem 1rem;
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease-out;
        }
        .table-fields.expanded {
            max-height: 600px;
            overflow-y: auto;
            transition: max-height 0.5s ease-in;
        }
        .field-detail {
            margin-bottom: 0.5rem;
            padding: 0.5rem;
            border: 1px solid #e9ecef;
            border-radius: 0.25rem;
        }
        .collapse-icon {
            transition: transform 0.3s ease;
        }
        .rotate {
            transform: rotate(180deg);
        }
        .field-item {
            margin-left: 1.5rem;
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
        }
        .badge {
            font-size: 0.75rem;
            margin-left: 0.5rem;
        }
        .required::after {
            content: "*"; 
            color: red;
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 d-none d-md-block sidebar">
                <div class="text-center mb-4">
                    <h3>数据管理</h3>
                </div>
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'datasource_list' %}">
                            <i class="bi bi-database me-2"></i>
                            数据源管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="{% url 'agent_management' %}">
                            <i class="bi bi-robot me-2"></i>
                            智能体管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'operation_log' %}">
                            <i class="bi bi-clock-history me-2"></i>
                            操作日志
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 主内容区 -->
            <main class="col-md-10 ms-sm-auto px-md-4 content">
                <!-- 顶部导航 -->
                <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
                    <div class="container-fluid">
                        <a href="{% url 'agent_management' %}" class="btn btn-outline-secondary me-2">
                            <i class="bi bi-arrow-left me-1"></i>
                            返回列表
                        </a>
                        <h4 class="mb-0">
                            {% if agent %}编辑智能体: {{ agent.name }}{% else %}新建智能体{% endif %}
                        </h4>
                        <div class="d-flex ms-auto gap-2">
                            {% if agent %}
                            <button type="button" class="btn btn-outline-success me-2" onclick="runAgent()">
                                <i class="bi bi-play me-1"></i>
                                立即执行
                            </button>
                            {% endif %}
                            <button class="btn btn-outline-secondary">
                                <i class="bi bi-person me-1"></i>
                                登录
                            </button>
                        </div>
                    </div>
                </nav>

                <!-- 智能体基本信息卡片 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">智能体基本信息</h5>
                    </div>
                    <div class="card-body">
                        <form id="agentForm">
                            {% csrf_token %}
                            {% if agent %}
                            <input type="hidden" name="agentId" value="{{ agent.id }}" />
                            {% endif %}

                            <div class="form-group">
                                <label for="agentName" class="required">智能体名称</label>
                                <input type="text" class="form-control" id="agentName" name="agentName" 
                                       value="{% if agent %}{{ agent.name }}{% endif %}" 
                                       placeholder="请输入智能体名称" required />
                            </div>

                            <div class="form-group">
                                <label for="agentDescription">智能体描述</label>
                                <textarea class="form-control" id="agentDescription" name="agentDescription" 
                                          rows="3" placeholder="请输入智能体描述">{% if agent %}{{ agent.description }}{% endif %}</textarea>
                            </div>

                            <div class="form-group">
                                <label for="datasourceSelect" class="required">关联数据源</label>
                                <select class="form-select" id="datasourceSelect" name="datasourceId" required placeholder="请选择数据源">
                                    <!-- <option value="">请选择数据源</option> -->
                                    {% for datasource in datasources %}
                                    <option value="{{ datasource.id }}" 
                                            {% if agent and datasource.id == agent.datasource_id %}selected{% endif %}>
                                        {{ datasource.name }} ({{ datasource.engine }})
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>

                            <div class="form-group">
                                <label class="required">执行方式</label>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="radio" name="executionType" id="manualExecution" 
                                           value="manual" {% if not agent or agent.execution_type == 'manual' %}checked{% endif %} />
                                    <label class="form-check-label" for="manualExecution">手动执行</label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="radio" name="executionType" id="intervalExecution" 
                                           value="interval" {% if agent and agent.execution_type == 'interval' %}checked{% endif %} />
                                    <label class="form-check-label" for="intervalExecution">间隔执行</label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="radio" name="executionType" id="cronExecution" 
                                           value="cron" {% if agent and agent.execution_type == 'cron' %}checked{% endif %} />
                                    <label class="form-check-label" for="cronExecution">Cron表达式</label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="radio" name="executionType" id="passiveExecution" 
                                           value="passive" {% if agent and agent.execution_type == 'passive' %}checked{% endif %} />
                                    <label class="form-check-label" for="passiveExecution">被动执行</label>
                                </div>
                            </div>

                            <div class="form-group" id="scheduleConfig" style="display: {% if agent and agent.execution_type != 'manual' %}block{% else %}none{% endif %}; margin-top: 15px;">
                                <div id="intervalConfig" style="display: {% if not agent or agent.execution_type == 'interval' %}block{% else %}none{% endif %}; margin-top: 15px;">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label for="intervalValue" class="required">间隔值</label>
                                            <input type="number" class="form-control" id="intervalValue" name="intervalValue" 
                                                   placeholder="请输入间隔值" min="1" 
                                                   value="{% if agent and agent.execution_type == 'interval' %}{{ agent.config_data.interval_value|default:1 }}{% else %}1{% endif %}" />
                                        </div>
                                        <div class="col-md-6">
                                            <label for="intervalUnit" class="required">时间单位</label>
                                            <select class="form-select" id="intervalUnit" name="intervalUnit">
                                                <option value="minutes" {% if agent and agent.config_data.interval_unit == 'minutes' %}selected{% endif %}>分钟</option>
                                                <option value="hours" {% if agent and agent.config_data.interval_unit == 'hours' %}selected{% endif %}>小时</option>
                                                <option value="days" {% if not agent or agent.config_data.interval_unit == 'days' %}selected{% endif %}>天</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="row mt-3">
                                        <div class="col-md-12">
                                            <label for="executionStartTime">开始时间（可选）</label>
                                            <input type="datetime-local" class="form-control" id="executionStartTime" name="executionStartTime" 
                                                   value="{% if agent and agent.execution_type == 'interval' and agent.execution_start_time %}{{ agent.execution_start_time|date:'Y-m-d\TH:i' }}{% endif %}" />
                                            <small class="form-text text-muted mt-1">若不设置，则立即开始执行</small>
                                        </div>
                                    </div>
                                </div>

                                <div id="cronConfig" style="display: {% if agent and agent.execution_type == 'cron' %}block{% else %}none{% endif %}; margin-top: 15px;">
                                    <label for="cronExpression" class="required">Cron表达式</label>
                                    <input type="text" class="form-control" id="cronExpression" name="cronExpression" 
                                           value="{% if agent and agent.execution_type == 'cron' %}{{ agent.cron_expression }}{% endif %}" 
                                           placeholder="例如: 0 0 * * * 表示每天午夜执行" />
                                    <small class="form-text text-muted mt-1">Cron表达式格式: 分钟 小时 日期 月份 星期</small>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="destinationAgent" class="required">目标智能体</label>
                                <input type="text" class="form-control" id="destinationAgent" name="destinationAgent" 
                                       value="{% if agent %}{{ agent.target_agent }}{% endif %}" 
                                       placeholder="请输入目标智能体名称" required />
                                <small class="form-text text-muted mt-1">数据抽取后发送到的目标智能体</small>
                            </div>

                            <!-- 表和字段展示部分 -->
                            <div class="form-group">
                                <label>您将同意智能体抽取以下字段</label>
                                <div class="table-selection" id="tableSelection">
                                    {% if agent and agent.selected_tables %}
                                        {% for table_name, fields in agent.selected_tables.items %}
                                        <div class="table-item mb-3">
                                            <div class="table-header bg-light p-2 rounded d-flex justify-content-between align-items-center">
                                                <div>
                                                    <strong class="text-primary">{{ table_name }}</strong>
                                                    <span class="badge bg-secondary ms-2">{{ fields|length }}个字段</span>
                                                </div>
                                                <i class="bi bi-chevron-down collapse-icon"></i>
                                            </div>
                                            <div class="table-fields mt-2 expanded">
                                                {% for field in fields %}
                                                <div class="field-detail mb-2 p-2 border rounded">
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <strong class="text-primary">{{ field }}</strong>
                                                        <span class="badge bg-info">{{ field }}</span>
                                                    </div>
                                                </div>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        {% endfor %}
                                    {% else %}
                                        <div class="text-center text-muted p-4" id="emptySelection">
                                            <i class="bi bi-database fs-1"></i>
                                            <p class="mt-2">{% if agent %}该智能体尚未配置表和字段{% else %}新建模式下请先选择数据源并配置表和字段{% endif %}</p>
                                        </div>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="d-flex justify-content-end gap-2 mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="window.location.href='{% url 'agent_management' %}'">取消</button>
                                <button type="submit" class="btn btn-primary">
                                    {% if agent %}更新智能体{% else %}创建智能体{% endif %}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
       // 获取配置的表和字段
    async function getConfigData(dataSource) {
      const response = await fetch(`/api/datasource/${dataSource}/config/`)
      const configData = await response.json()
      // 现在可以直接使用 configData
      console.log(configData)
      return configData
    }
    // 获取数据库表
    async function getTableData(dataSource) {
      const response = await fetch(`/api/datasource/${dataSource}/tables/`)
      const tableData = await response.json()
      // 现在可以直接使用 tableData
      console.log(tableData)
      return tableData
    }

    // 进入页面后初始化
    window.onload = async function() { 
      const datasourceSelect = document.getElementById('datasourceSelect');
      const dataSource = datasourceSelect.value;
      
      if (dataSource) {
          try {
              const tableData = await getTableData(dataSource);
              const configData = await getConfigData(dataSource);
              fillTableAndFields(tableData, configData);
          } catch (error) {
              console.error('初始化加载表和字段数据失败:', error);
          }
      }
    }
    
        // 执行方式切换
        document.querySelectorAll('input[name="executionType"]').forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'interval') {
                    document.getElementById('scheduleConfig').style.display = 'block';
                    document.getElementById('intervalConfig').style.display = 'block';
                    document.getElementById('cronConfig').style.display = 'none';
                } else if (this.value === 'cron') {
                    document.getElementById('scheduleConfig').style.display = 'block';
                    document.getElementById('intervalConfig').style.display = 'none';
                    document.getElementById('cronConfig').style.display = 'block';
                } else if (this.value === 'passive') {
                    document.getElementById('scheduleConfig').style.display = 'none';
                } else {
                    document.getElementById('scheduleConfig').style.display = 'none';
                }
            });
        });

        // 获取数据源，更新表和字段，当选择数据源时触发
        document.getElementById('datasourceSelect').addEventListener('change', async function() {
            const dataSource = this.value;
            if (!dataSource) return;
            
            try {
                // 获取配置的表和字段
                const tableData = await getTableData(dataSource);
                const configData = await getConfigData(dataSource);
                fillTableAndFields(tableData, configData);
            } catch (error) {
                console.error('获取表和字段数据失败:', error);
                const tableSelection = document.querySelector('.table-selection');
                tableSelection.innerHTML = `
                  <div class="text-center text-muted p-4">
                    <i class="bi bi-exclamation-triangle fs-1"></i>
                    <p class="mt-2">获取数据失败，请检查数据源配置</p>
                  </div>
                `;
            }
        });


        // 根据配置的表和字段，展示表和字段
        function fillTableAndFields(tableData, configData) {
          // 清空之前的内容
          const tableSelection = document.querySelector('.table-selection');
          tableSelection.innerHTML = '';
          
          if (!configData || !configData.selected_tables || configData.selected_tables.length === 0) {
            tableSelection.innerHTML = `
              <div class="text-center text-muted p-4">
                <i class="bi bi-database fs-1"></i>
                <p class="mt-2">该数据源尚未配置表和字段</p>
              </div>
            `;
            return;
          }

          if (!tableData || !tableData.tables) {
            tableSelection.innerHTML = `
              <div class="text-center text-muted p-4">
                <i class="bi bi-exclamation-triangle fs-1"></i>
                <p class="mt-2">无法获取表结构信息</p>
              </div>
            `;
            return;
          }
          
          // 遍历配置的表和字段
          configData.selected_tables.forEach(tableConfig => {
            const tableName = tableConfig.table;
            const selectedFields = tableConfig.fields || [];
            
            // 在tableData中找到对应的表信息
            const tableInfo = tableData.tables.find(t => t.name === tableName);
            if (!tableInfo) return;

            const tableDiv = document.createElement('div');
            tableDiv.className = 'table-item mb-3';
            
            let fieldsHtml = '';
            let fieldCount = 0;

            // 创建字段映射，方便查找
            const fieldMap = {};
            if (tableInfo.fields) {
                tableInfo.fields.forEach(field => {
                    fieldMap[field.name] = field;
                });
            }

            if (selectedFields && selectedFields.length > 0) {
              fieldCount = selectedFields.length;
              // 显示选中的字段（包含详细信息）
              selectedFields.forEach(fullFieldName => {
                const fieldName = fullFieldName.includes('.') ? fullFieldName.split('.').pop() : fullFieldName;
                const fieldInfo = fieldMap[fieldName];
                if (fieldInfo) {
                  fieldsHtml += `
                    <div class="field-detail mb-2 p-2 border rounded">
                      <div class="d-flex justify-content-between align-items-center">
                        <strong class="text-primary">${fieldName}</strong>
                        <span class="badge bg-info">${fieldInfo.type}</span>
                      </div>
                      ${fieldInfo.description ? `<small class="text-muted">${fieldInfo.description}</small>` : ''}
                      ${fieldInfo.nullable ? '<small class="badge bg-warning">可空</small>' : '<small class="badge bg-success">必填</small>'}
                    </div>
                  `;
                } else {
                  fieldsHtml += `
                    <div class="field-detail mb-2 p-2 border rounded">
                      <strong class="text-primary">${fieldName}</strong>
                    </div>
                  `;
                }
              });
            } else {
              // 显示所有字段（包含详细信息）
              fieldCount = tableInfo.field_count || (tableInfo.fields && tableInfo.fields.length) || 0;
              if (tableInfo.fields && tableInfo.fields.length > 0) {
                fieldsHtml = tableInfo.fields.map(field => 
                  `
                    <div class="field-detail mb-2 p-2 border rounded">
                      <div class="d-flex justify-content-between align-items-center">
                        <strong class="text-primary">${field.name}</strong>
                        <span class="badge bg-info">${field.type}</span>
                      </div>
                      ${field.description ? `<small class="text-muted">${field.description}</small>` : ''}
                      ${field.nullable ? '<small class="badge bg-warning">可空</small>' : '<small class="badge bg-success">必填</small>'}
                    </div>
                  `
                ).join('');
              } else {
                fieldsHtml = '<small class="text-muted">已选择整个表</small>';
              }
            }
            
            tableDiv.innerHTML = `
              <div class="table-header bg-light p-2 rounded d-flex justify-content-between align-items-center">
                <div>
                  <strong class="text-primary">${tableName}</strong>
                  <span class="badge bg-secondary ms-2">${fieldCount}个字段</span>
                </div>
                <i class="bi bi-chevron-down collapse-icon"></i>
              </div>
              <div class="table-fields mt-2 expanded">
                ${fieldsHtml}
              </div>
            `;
            
            // 添加展开折叠功能
            const header = tableDiv.querySelector('.table-header');
            const fields = tableDiv.querySelector('.table-fields');
            const icon = tableDiv.querySelector('.collapse-icon');
            
            header.addEventListener('click', function() {
              fields.classList.toggle('expanded');
              icon.classList.toggle('rotate');
            });
            
            tableSelection.appendChild(tableDiv);
          });
        }

        {% if agent %}
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
          // 初始化执行方式对应的显示状态
          const selectedExecutionType = document.querySelector('input[name="executionType"]:checked');
          if (selectedExecutionType) {
              const event = new Event('change');
              selectedExecutionType.dispatchEvent(event);
          }
          
          // 编辑模式下初始化已选表和字段
          {% if selected_tables_json %}
          window.selectedTables = {{ selected_tables_json|safe }};
          {% else %}
          window.selectedTables = {};
          {% endif %}
        });

        // 运行智能体
        function runAgent() {
            alert('执行智能体功能暂未实现');
        }
        {% else %}
        // 新建模式初始化
        document.addEventListener('DOMContentLoaded', function() {
          window.selectedTables = {};
        });
        {% endif %}

        // 表单提交处理
        document.getElementById('agentForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            // 数据验证
            if (!data.agentName || !data.datasourceId || !data.destinationAgent) {
                alert('请填写所有必填字段');
                return;
            }
            
            // 根据执行方式验证额外字段
            if (data.executionType === 'interval') {
                if (!data.intervalValue || !data.intervalUnit) {
                    alert('请填写间隔执行的配置');
                    return;
                }
            } else if (data.executionType === 'cron') {
                if (!data.cronExpression) {
                    alert('请填写Cron表达式');
                    return;
                }
            }
            
            try {
                    const url = '{% if agent %}{% url "agent_form" agent.id %}{% else %}{% url "agent_form" %}{% endif %}';
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                        },
                        body: JSON.stringify({
                            agentName: data.agentName,
                            agentDescription: data.agentDescription || '',
                            datasourceId: data.datasourceId,
                            executionType: data.executionType,
                            destinationAgent: data.destinationAgent,
                            cronExpression: data.cronExpression || '',
                            executionStartTime: data.executionType === 'interval' ? data.executionStartTime || Date.now() : null,
                            intervalValue: data.executionType === 'interval' ? data.intervalValue : '',
                            intervalUnit: data.executionType === 'interval' ? data.intervalUnit : '',
                            selected_tables: collectSelectedTables()
                        })
                    })
                
                const result = await response.json();
                
                if (response.ok) {
                    alert(result.message || '{% if agent %}智能体更新成功{% else %}智能体创建成功{% endif %}');
                    if (result.redirect_url) {
                        window.location.href = result.redirect_url;
                    } else {
                        window.location.href = '{% url "agent_management" %}';
                    }
                } else {
                    alert('操作失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('Error:', error);
                alert('网络错误，请稍后重试');
            }
        });
        
        // 收集选中的表和字段
        function collectSelectedTables() {
            const tables = {};
            const tableItems = document.querySelectorAll('.table-item');
            
            tableItems.forEach(item => {
                const tableName = item.querySelector('.text-primary').textContent;
                const fields = [];
                const fieldDetails = item.querySelectorAll('.field-detail');
                
                fieldDetails.forEach(fieldDetail => {
                    const fieldName = fieldDetail.querySelector('strong').textContent;
                    fields.push(fieldName);
                });
                
                if (fields.length > 0) {
                    tables[tableName] = fields;
                }
            });
            
            return tables;
        }
    </script>
</body>
</html>